package com.atguigu.tingshu.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private RabbitService rabbitService;

	@Override
	public BigDecimal getTrackBreakSecond(Long trackId, Long userId) {
		//根据用户id声音id判断mongoDB中是否有播放记录
		//mongoDB中怎么存储数据：数据库（tingshu），集合（userId），文档（UserListenProcess ObjectId id, trackId,second,createTime,updateTime）
		Query query = Query.query(Criteria.where("trackId").is(trackId));
        //获取集合名称
		String collectionName = this.getCollectionName(userId);
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
        if (null != userListenProcess){
                  return userListenProcess.getBreakSecond();
		}
		return new BigDecimal("0");
	}

	@Override
	public void updateListenProcess(UserListenProcessVo userListenProcessVo, Long userId) {
		//构建查询条件
		Query query = Query.query(Criteria.where("trackId").is(userListenProcessVo.getTrackId()));
		//获取集合名称
		String collectionName = this.getCollectionName(userId);
		//创建对象
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		if (null != userListenProcess){
			//更新修改时间
			userListenProcess.setUpdateTime(new Date());
			userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
		}else{
			//创建对象
			userListenProcess = new UserListenProcess();
			//属性拷贝
			BeanUtils.copyProperties(userListenProcessVo,userListenProcess);
			userListenProcess.setUserId(userId);
			userListenProcess.setCreateTime(new Date());
			userListenProcess.setUpdateTime(new Date());
		}
		//更新保存数据
		mongoTemplate.save(userListenProcess,collectionName);
		//防止恶意刷新播放量
		//发送消息播放量＋1，声音和专辑都＋1
		String key = "track:play:stat:" + userId + ":" + userListenProcessVo.getTrackId();
		//判断key是否在缓存中存在
		Boolean result = this.redisTemplate.opsForValue().setIfAbsent(key, "1", 1, TimeUnit.DAYS);
		if (result){
			//	执行成功; 说明第一次播放; albumId, trackId;
			TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
			trackStatMqVo.setTrackId(userListenProcessVo.getTrackId());
			trackStatMqVo.setAlbumId(userListenProcessVo.getAlbumId());
			trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
			trackStatMqVo.setCount(1);
			//	业务编号，防止消息重复消费!
			String businessNo = UUID.randomUUID().toString().replaceAll("-", "");
			trackStatMqVo.setBusinessNo(businessNo);
			//	发送消息;
			this.rabbitService.sendMessage(MqConst.EXCHANGE_TRACK,MqConst.ROUTING_TRACK_STAT_UPDATE, JSON.toJSONString(trackStatMqVo));
		}

	}

	@Override
	public Map<String, Object> getLatelyTrack(Long userId) {
		//创建一个map集合
		HashMap<String, Object> map = new HashMap<>();
		//查询mongoDB
		String collectionName = this.getCollectionName(userId);
		Query query = new Query();
		query.with(Sort.by(Sort.Direction.DESC, "updateTime")).limit(1);
		List<UserListenProcess> userListenProcessList = this.mongoTemplate.find(query, UserListenProcess.class, collectionName);
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		System.out.println(userListenProcess.getTrackId()+":\t"+userListenProcess.getAlbumId());
		//	存储数据;
		map.put("trackId",userListenProcessList.get(0).getTrackId());
		map.put("albumId",userListenProcessList.get(0).getAlbumId());
		return map;
	}

	private String getCollectionName(Long userId) {
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		return collectionName;
	}
}
